#!/bin/bash
# @Time     : 2022-1-21
# @Description  : domain name https cert check

source /etc/profile

# The script of bash path.
# bash_dir=$(cd $(dirname $0) && pwd)

# The script name.
# self_name=$(basename ${0})

# check Parma
if [ $# != 1 ]; then
  echo -e "\033[31mERROR\033[0m Should be e.g.: \033[32m$0 30\033[0m"
  exit 1; 
fi

# print comma
function print_comma() {
    if [ "$1" != "$2" ]; then
			echo ","
	fi
}

# Expiration time
ex_day=$1

# The domain name list
readFile="/home/ampdcp/domain_ssl.info"
totle=$(grep -v '^#' ${readFile} | wc -l)
# print json
printf \
'
{
    "messageCode": "success",
    "message": "",
    "data": {
'   
grep -n -v '^#' ${readFile} | while read line; do
    num=$(echo ${line} | awk -F ':' '{print $1}')
    get_domain=$(echo ${line} | awk -F ':' '{print $2}')
    get_port=$(echo ${line} | awk -F ':' '{print $3}')

    # Get Date -- curl
    cert_endtime=$(echo | openssl s_client -servername ${get_domain} -connect ${get_domain}:${get_port} 2>/dev/null | openssl x509 -noout -dates |grep 'After'| awk -F '=' '{print $2}'| awk -F ' +' '{print $1,$2,$4 }')
    # Date to timestamp
    cert_endtime_timestamp=$(date +%s -d "${cert_endtime}")
    # Get Now Date to timestamp
    nowtime_timestamp=$(date +%s -d "$(date | awk -F ' +'  '{print $2,$3,$6}')")
    # day
    day=$(($((${cert_endtime_timestamp}-${nowtime_timestamp}))/(60*60*24)))
    domain_s=$(echo ${get_domain} | sed 's/\./_/g')
    echo \
        '"'${domain_s}'"': '"'${day}'"'$(print_comma $num $totle)

    #if [ ${day} -lt ${ex_day} ]; then
    #  echo "${get_domain} https证书有效期当前还剩${day}天，少于${ex_day}天，危险"
      # other option
    #else
    #  echo "${get_domain} https证书有效期当前还剩${day}天，${ex_day}天以上，安全"
    #fi
done
    echo \
'}}'
